package com.seal.commons.utils.template.engine;


import com.seal.commons.utils.template.AbstractTemplateEngine;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * func 模板引擎
 * Date 2019-04-23 15:04 <br/>
 * @author yong.huang
 * @since JDK 1.8
 */
public class FreemarkerTemplateEngine extends AbstractTemplateEngine {

    private static Logger log = LoggerFactory.getLogger(FreemarkerTemplateEngine.class);

    public static final String DEFAULT_ENCODING = "UTF-8";

    public static final String BASE_PACKAGE_PATH = "/";
    private Configuration configuration ;

    public FreemarkerTemplateEngine(TemplateLoader templateLoader){
        this.configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        this.configuration.setDefaultEncoding(DEFAULT_ENCODING);
        this.configuration.setTemplateLoader(templateLoader);
    }

    @Override
    public void render(String name, Map<?, ?> bindingMap, Writer writer) {
        try {
            Template template = this.configuration.getTemplate(name);
            template.process(bindingMap, writer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
    }
}
